﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using EnergyConsumptionMonitorSystem.Models;
using EnergyConsumptionMonitorSystem.Components;
using System.Security;
using System.Runtime.InteropServices;
using System.Windows;

namespace EnergyConsumptionMonitorSystem.MainWindowTabItem
{
    public class RegisterUCViewModel : TabItemContentUCViewModel
    {

        private bool? _isUserNameValidated = null;
        public bool? IsUserNameValidated
        {
            get { return this._isUserNameValidated; }
            set
            {
                if (this._isUserNameValidated != value)
                {
                    this._isUserNameValidated = value;
                    NotifyPropertyChanged("IsUserNameValidated");
                }
            }
        }

        private bool? _isPasswordValidated = null;
        public bool? IsPasswordValidated
        {
            get { return this._isPasswordValidated; }
            set
            {
                if (this._isPasswordValidated != value)
                {
                    this._isPasswordValidated = value;
                    NotifyPropertyChanged("IsPasswordValidated");
                }
            }
        }


        private string _userName = "";
        public string UserName
        {
            get { return this._userName; }
            set
            {
                if (this._userName != value)
                {
                    this._userName = value;
                    NotifyPropertyChanged("UserName");
                }
            }
        }

        public delegate void HarvestPasswordHandler(object sender, PasswordEventArgs e);
        public event HarvestPasswordHandler HarvestPasswordEvent;
        public event HarvestPasswordHandler HarvestConfirmedPasswordEvent;

        private ICommand _validateUserNameCommand;
        public ICommand ValidateUserNameCommand { get { return this._validateUserNameCommand; } }

        private ICommand _registerCommand;
        public ICommand RegisterCommand { get { return this._registerCommand; } }

        public RegisterUCViewModel()
            : base()
        {
            this._view = new RegisterUC(this);
            this._view.DataContext = this;

            this._validateUserNameCommand = new Command(new Action<object>(this.ValidateUserName));
            this._registerCommand = new Command(new Action<object>(this.Register));
        }

        private void ValidateUserName(object o)
        {
            if (this.UserName != "")
            {
                this.IsUserNameValidated = !Singleton<DBManager>.Instance.ExistUserName(this.UserName);
            }
            else
            {
                this.IsUserNameValidated = null;
            }
        }

        private void Register(object o)
        {
            if (this.HarvestPasswordEvent != null && this.HarvestConfirmedPasswordEvent != null)
            {
                PasswordEventArgs pwd = new PasswordEventArgs();
                PasswordEventArgs pwdConfirmed = new PasswordEventArgs();
                this.HarvestPasswordEvent(this, pwd);
                this.HarvestConfirmedPasswordEvent(this, pwdConfirmed);
                string password = ConvertToUnsecureString(pwd.Password);
                string passwordConfirmed = ConvertToUnsecureString(pwdConfirmed.Password);
                if (password != "" && passwordConfirmed != "" && this.UserName != "")
                {
                    if (this.IsUserNameValidated == true)
                    {
                        if (password.Equals(passwordConfirmed))
                        {
                            Singleton<DBManager>.Instance.CreateNewUser(this.UserName, password);
                            MessageBox.Show("请重新登录。", "注册成功");
                            this.CloseRequest(null);
                        }
                        else
                        {
                            this.IsPasswordValidated = false;
                            MessageBox.Show("密码不一致，请重新输入。", "注册失败");
                        }
                    }
                    else
                    {
                        MessageBox.Show("该用户名已存在。", "注册失败");
                    }
                }
                else
                {
                    MessageBox.Show("请填写完整用户名及密码。","注册失败");
                }
            }
        }

        protected override void tabItem_ClosingEvent(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = false;
        }

        private string ConvertToUnsecureString(SecureString securePassword)
        {
            if (securePassword == null)
                throw new ArgumentNullException("securePassword");

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
    }
}
